<?php

namespace Lib;

class Controller
{
    public function __construct()
    {

    }

    /**
     * 模版传值
     *
     * @param string $k 键
     * @param mixed $v  值
     * @return null
     */
    public static function assign($k, $v = '')
    {
        self::getView()->assign($k, $v);
    }

    /**
     * @Brief 加载模版
     * @param string $tpl 模版路径
     * @return null
     */
    public static function display($tpl)
    {
        self::getView()->display($tpl);
    }


    /**
     * @Brief  获取模版内容不输出
     * @Params string $tpl
     * @Return string
     */
    public static function fetch($tpl, $display = true)
    {

        return self::getView()->fetch($tpl, '', '', $display);
    }

    /**
     * 加载视图类
     */
    public static function getView()
    {
        $appPath = ROOT_PATH . '/App/' . App_Name;

        static $tpl = null;
        if (null === $tpl) {
            $tpl                  = new \Smarty();
            $tpl->template_dir    = $appPath . "/View";
            $tpl->compile_dir     = $appPath . "/Cache/Compile";
            $tpl->cache_dir       = $appPath . "/Cache/Cache";  //指定缓存存放目录
            $tpl->caching         = false;  //关闭缓存（设置为true表示启用缓存）
            $tpl->left_delimiter  = "{";  //指定左标签
            $tpl->right_delimiter = "}";  //指定右标签
            $tpl->use_sub_dirs    = true;
            $tpl->_dir_perms      = 0777;
            $tpl->addPluginsDir(LIB_PATH . '/Smarty_plugins');

            if (!is_dir($tpl->cache_dir)) {
                mkdir($tpl->cache_dir, 0755, true);
            }
        }

        return $tpl;
    }

    /**
     * json数据返回
     *
     * @param int $code
     * @param string $message
     * @param mixed $message
     */
    public function jsonReturn($code = 10000, $message = 'success', $info)
    {
        $result['code']    = $code;
        $result['message'] = $message;
        $result['info']    = $info;

        header("Content-Type:text/html; charset=utf-8");
        exit(json_encode($result));
    }

    /**
     * 检测管理员是否登录
     *
     * @return bool
     */
    public function checkAdminLogin()
    {
        $ret     = false;
        $adminId = $_SESSION['adminId'];
        if (!empty($adminId)) {
            $ret = true;
        }

        return $ret;
    }
}